import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { User, LoginForm } from "@/entity/User";
import { login, getUserInfo, logout } from "@/api/user";
import { watch } from "vue";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    userInfo: {} as User,
  }),
  getters: {
    // 是否已经登录
    isLogin(state) {
      return !!(state.token && state.userInfo.userId);
    },
  },
  actions: {
    // 登录
    async login(form: LoginForm) {
      const token = await login(form);

      this.token = token;

      return this.getUserInfo();
    },
    // 获取用户信息
    async getUserInfo() {
      const userInfo = await getUserInfo();

      this.userInfo = userInfo;

      return userInfo;
    },
    // 退出登录
    async logout() {
      // 重置数据
      this.$reset();
      // 删除 token
      removeToken();

      // 调用接口
      logout();
    },
  },
});

// 监听 token 改变
watch(
  () => useUserStore().token,
  (token) => {
    token && setToken(token);
  }
);
